﻿/*
 * 实现两个可自行输入矩阵维数的矩阵相乘过程，并显示输出相乘后的结果
 */

using System.Reflection;
using System.Runtime.InteropServices.Marshalling;

static void Main(string[] args)
{
    int M, N, P;
    int i, j;
    string strM;
    string strN;
    string strP;
    string tempstr;
    Console.WriteLine("请输入矩阵A的维数(M,N):");
    Console.Write("请先输入矩阵A的M值:");
    strM = Console.ReadLine();
    M = int.Parse(strM);
    Console.Write("接着输入矩阵A的N值:");
    strN = Console.ReadLine();
    N = int.Parse(strN);
    int[,] A = new int[M, N];
    Console.WriteLine("请输入矩阵A的各个元素：");
    Console.WriteLine("注意！每输入一个值按下Enter键确认输入");
    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++)
        {
            Console.Write("a" + i + j + "=");
            tempstr = Console.ReadLine();
            A[i, j] = int.Parse(tempstr);
        }
    }

    Console.WriteLine("请输入矩阵B的维数(N,P)");
    Console.Write("请先输入矩阵B的N值：");
    strN = Console.ReadLine();
    N = int.Parse(strN);

    Console.Write("接着输入矩阵B的P值：");
    strP = Console.ReadLine();
    P = int.Parse(strP);

    int[,] B = new int[N, P];
    Console.WriteLine("请输入矩阵B的各个元素：");
    Console.WriteLine("注意！每输入一个值按下Enter键确认输入");
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < P; j++)
        {
            Console.Write("b" + i + j + "=");
            tempstr = Console.ReadLine();
            B[i, j] = int.Parse(tempstr);
        }
    }

    int[,] C = new int[M, P];
    MatrixMultiply(A, B, C, M, N, P);
    Console.WriteLine("[A * B 的结果是]");
    for (i = 0; i < M; i++)
    {
        for (j = 0; j < P; j++)
        {
            Console.Write(C[i, j]);
            Console.Write('\t');
        }
    }
    Console.WriteLine();
    Console.ReadLine();

}

// 矩阵相乘
static void MatrixMultiply(int[,] arrA, int[,] arrB, int[,] arrC, int M, int N, int P)
{
    int i, j, k, Temp;
    if (M <= 0 || N <= 0 || P <= 0)
    {
        Console.WriteLine("[错误：维数M,N,P必须大于0]");
        return;
    }

    for (i = 0; i < M; i++)
    {
        for (j = 0; j < P; j++)
        {
            Temp = 0;
            for (k = 0; k < N; k++)
            {
                Temp = Temp + arrA[i, k] * arrB[k, j];
            }

            arrC[i, j] = Temp;
        }
    }
}